package com.marquis.cloud.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录
 */
@Controller
public class LoginController {

    /**
     * 登录验证
     * @return 验证结果
     */
    @RequestMapping(value = "login")
    public String login(HttpServletRequest request, String userName, String password){
        String error = null;
        try {
            Subject subject = SecurityUtils.getSubject();
            Object principal = subject.getPrincipal();
            // 如果已经登录，则跳转到管理首页
            if (principal != null) {
                return "redirect:/index"; // 首页
            }
            if(StringUtils.isEmpty(userName) && StringUtils.isEmpty(password)){
                return "login";
            }
            if(StringUtils.isEmpty(userName)){
                error = "请输入用户名!";
            }else {
                request.setAttribute("userName", userName);
            }
            if(StringUtils.isEmpty(password)){
                error = "请输入密码";
            }
            if(StringUtils.isEmpty(error)){
                UsernamePasswordToken token = new UsernamePasswordToken();
                //设置用户名
                token.setUsername(userName);
                //设置密码
                token.setPassword(password.toCharArray());
                //是否记住我
                token.setRememberMe(true);
                //登录
                subject.login(token);
            }
        } catch (UnknownAccountException e) {
            error = "用户不存在";
        } catch (IncorrectCredentialsException e){
            error = "密码错误";
        } catch (LockedAccountException e){
            error = "用户已锁定";
        } catch (Exception e){
            error = "登录失败，请重新登录";
        }
        if(!StringUtils.isEmpty(error)){
            request.setAttribute("error", error);
            return "login";
        }
        return "redirect:/index";
    }
}
